package com.madixin.madichat.ui.feature.chat

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import com.madixin.madichat.model.ChatSession
import com.madixin.madichat.model.Message
import com.madixin.madichat.ui.theme.Blue
import com.madixin.madichat.ui.theme.LightGray
import kotlinx.coroutines.launch

@Composable
fun ChatScreen(
    viewModel: ChatViewModel,
    onNavigateToLogin: () -> Unit
) {
    val sessions by viewModel.sessions.collectAsState()
    val currentSessionId by viewModel.currentSessionId.collectAsState()
    val messages by viewModel.messages.collectAsState()
    val inputText by viewModel.inputText.collectAsState()
    val isDrawerOpen by viewModel.isDrawerOpen.collectAsState()
    val showEditDialog by viewModel.showEditDialog.collectAsState()
    val showDeleteDialog by viewModel.showDeleteDialog.collectAsState()
    val sessionToEdit by viewModel.sessionToEdit.collectAsState()
    val newSessionTitle by viewModel.newSessionTitle.collectAsState()
    val errorMessage by viewModel.errorMessage.collectAsState()
    
    val scaffoldState = rememberScaffoldState()
    val scope = rememberCoroutineScope()
    val listState = rememberLazyListState()
    val context = androidx.compose.ui.platform.LocalContext.current  // 在这里获取Context

    // 显示错误Toast
    LaunchedEffect(errorMessage) {
        errorMessage?.let { error ->
            // 显示Toast
            android.widget.Toast.makeText(
                context,  // 使用外部获取的context
                error,
                android.widget.Toast.LENGTH_LONG
            ).show()
            // 清除错误消息，避免重复显示
            viewModel.clearErrorMessage()
        }
    }
    
    // 当消息列表更新时，滚动到底部
    LaunchedEffect(messages.size) {
        if (messages.isNotEmpty()) {
            listState.animateScrollToItem(messages.size - 1)
        }
    }

    Scaffold(
        scaffoldState = scaffoldState,
        drawerContent = {
            ChatDrawer(
                sessions = sessions,
                currentSessionId = currentSessionId,
                onSessionSelected = { viewModel.selectSession(it.id) },
                onNewChat = { viewModel.createNewChat() },
                onEditSession = { viewModel.showEditSessionDialog(it) },
                onDeleteSession = { viewModel.showDeleteSessionDialog(it) },
                onLogout = {
                    viewModel.logout()
                    onNavigateToLogin()
                }
            )
        },
        drawerGesturesEnabled = true,
        topBar = {
            ChatTopBar(
                currentSession = sessions.find { it.id == currentSessionId },
                onMenuClick = { viewModel.toggleDrawer() },
                onEditTitle = { session -> session?.let { viewModel.showEditSessionDialog(it) } }
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(LightGray)
        ) {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                // 消息列表
                LazyColumn(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp),
                    state = listState,
                    contentPadding = PaddingValues(vertical = 8.dp)
                ) {
                    items(messages) { message ->
                        MessageItem(
                            message = message,
                            modifier = Modifier.padding(vertical = 4.dp)
                        )
                    }
                }
                
                // 输入区域
                ChatInput(
                    text = inputText,
                    onTextChange = { viewModel.updateInputText(it) },
                    onSendClick = { viewModel.sendMessage() },
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color.White)
                        .padding(8.dp)
                )
            }
            
            // 编辑会话名称对话框
            if (showEditDialog && sessionToEdit != null) {
                EditSessionDialog(
                    title = newSessionTitle,
                    onTitleChange = { viewModel.updateNewSessionTitle(it) },
                    onDismiss = { viewModel.hideEditSessionDialog() },
                    onConfirm = { viewModel.updateSessionTitle() }
                )
            }
            
            // 删除会话确认对话框
            if (showDeleteDialog && sessionToEdit != null) {
                DeleteConfirmDialog(
                    onDismiss = { viewModel.hideDeleteSessionDialog() },
                    onConfirm = { viewModel.deleteSession() }
                )
            }
        }
    }
    
    // 处理抽屉状态
    LaunchedEffect(isDrawerOpen) {
        if (isDrawerOpen) {
            scope.launch { scaffoldState.drawerState.open() }
        } else {
            scope.launch { scaffoldState.drawerState.close() }
        }
    }
}

@Composable
fun ChatDrawer(
    sessions: List<ChatSession>,
    currentSessionId: String?,
    onSessionSelected: (ChatSession) -> Unit,
    onNewChat: () -> Unit,
    onEditSession: (ChatSession) -> Unit,
    onDeleteSession: (ChatSession) -> Unit,
    onLogout: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxHeight()
            .width(280.dp)
            .background(Color.White)
    ) {
        // 抽屉顶部
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(Blue)
                .padding(vertical = 16.dp, horizontal = 16.dp)
        ) {
            Text(
                text = "MadiChat",
                color = Color.White,
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold
            )
        }
        
        // 新建聊天按钮
        Button(
            onClick = onNewChat,
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            colors = ButtonDefaults.buttonColors(backgroundColor = Blue)
        ) {
            Icon(
                imageVector = Icons.Default.Add,
                contentDescription = "新建聊天",
                tint = Color.White
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text("新建聊天", color = Color.White)
        }
        
        // 会话列表
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
        ) {
            items(sessions) { session ->
                SessionItem(
                    session = session,
                    isSelected = session.id == currentSessionId,
                    onClick = { onSessionSelected(session) },
                    onEdit = { onEditSession(session) },
                    onDelete = { onDeleteSession(session) }
                )
            }
        }
        
        // 底部用户信息和退出按钮
        Divider()
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 用户头像
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(Blue),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "用",
                    color = Color.White,
                    fontWeight = FontWeight.Bold
                )
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 用户信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = "用户",
                    fontWeight = FontWeight.Medium,
                    fontSize = 16.sp
                )
                Text(
                    text = "138****8000",
                    color = Color.Gray,
                    fontSize = 14.sp
                )
            }
            
            // 退出按钮
            IconButton(onClick = onLogout) {
                Icon(
                    imageVector = Icons.Default.ExitToApp,
                    contentDescription = "退出登录",
                    tint = Color.Gray
                )
            }
        }
    }
}

@Composable
fun ChatTopBar(
    currentSession: ChatSession?,
    onMenuClick: () -> Unit,
    onEditTitle: (ChatSession?) -> Unit
) {
    TopAppBar(
        title = {
            if (currentSession != null) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onEditTitle(currentSession) }
                ) {
                    Text(currentSession.title)
                    Spacer(modifier = Modifier.width(4.dp))
                    Icon(
                        imageVector = Icons.Default.Edit,
                        contentDescription = "编辑标题",
                        modifier = Modifier.size(16.dp)
                    )
                }
            } else {
                Text("MadiChat")
            }
        },
        navigationIcon = {
            IconButton(onClick = onMenuClick) {
                Icon(Icons.Default.Menu, contentDescription = "菜单")
            }
        },
        backgroundColor = Color.White,
        elevation = 4.dp
    )
}

@Composable
fun MessageItem(
    message: Message,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxWidth(),
        horizontalAlignment = if (message.isUser) Alignment.End else Alignment.Start
    ) {
        // 思考过程（仅AI消息显示）
        if (!message.isUser && message.thinkingProcess != null) {
            Text(
                text = message.thinkingProcess,
                color = Color.Gray,
                fontSize = 12.sp,
                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
            )
        }
        
        Row(
            verticalAlignment = Alignment.Bottom,
            horizontalArrangement = if (message.isUser) Arrangement.End else Arrangement.Start,
            modifier = Modifier.fillMaxWidth()
        ) {
            // 头像（仅AI消息显示在左侧）
            if (!message.isUser) {
                Box(
                    modifier = Modifier
                        .size(36.dp)
                        .clip(CircleShape)
                        .background(Blue),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "AI",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 14.sp
                    )
                }
                Spacer(modifier = Modifier.width(8.dp))
            }
            
            // 消息内容
            Column {
                Surface(
                    shape = RoundedCornerShape(12.dp),
                    color = if (message.isUser) Blue else Color.White,
                    elevation = 1.dp
                ) {
                    Text(
                        text = message.content,
                        color = if (message.isUser) Color.White else Color.Black,
                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)
                    )
                }
                
                Spacer(modifier = Modifier.height(4.dp))
                
                // 时间戳
                Text(
                    text = message.timestamp,
                    fontSize = 12.sp,
                    color = Color.Gray,
                    modifier = Modifier.padding(horizontal = 4.dp)
                )
            }
            
            // 头像（仅用户消息显示在右侧）
            if (message.isUser) {
                Spacer(modifier = Modifier.width(8.dp))
                Box(
                    modifier = Modifier
                        .size(36.dp)
                        .clip(CircleShape)
                        .background(Color.LightGray),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "用",
                        color = Color.DarkGray,
                        fontWeight = FontWeight.Bold,
                        fontSize = 14.sp
                    )
                }
            }
        }
    }
}

@Composable
fun ChatInput(
    text: String,
    onTextChange: (String) -> Unit,
    onSendClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 输入框
        TextField(
            value = text,
            onValueChange = onTextChange,
            modifier = Modifier
                .weight(1f)
                .heightIn(min = 40.dp, max = 120.dp),
            placeholder = { Text("输入消息...") },
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = LightGray,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent
            ),
            shape = RoundedCornerShape(20.dp)
        )
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 发送按钮
        IconButton(
            onClick = onSendClick,
            enabled = text.isNotBlank(),
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .background(if (text.isNotBlank()) Blue else Color.LightGray)
        ) {
            Icon(
                imageVector = Icons.Default.Send,
                contentDescription = "发送",
                tint = Color.White
            )
        }
    }
}

@Composable
fun SessionItem(
    session: ChatSession,
    isSelected: Boolean,
    onClick: () -> Unit,
    onEdit: () -> Unit,
    onDelete: () -> Unit
) {
    var showMenu by remember { mutableStateOf(false) }
    
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(if (isSelected) LightGray else Color.Transparent)
            .clickable { onClick() }
            .padding(horizontal = 16.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 会话图标
        // 使用已有图标，如 Comment 或其他适合的图标
        Icon(
            imageVector = Icons.Default.Comment, // 或其他合适的图标
            contentDescription = "聊天",
            tint = if (isSelected) Blue else Color.Gray,
            modifier = Modifier.size(24.dp)
        )
        
        Spacer(modifier = Modifier.width(12.dp))
        
        // 会话信息
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = session.title,
                fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                color = if (isSelected) Blue else Color.Black
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            Text(
                text = session.lastUpdateTime,
                fontSize = 12.sp,
                color = Color.Gray
            )
        }
        
        // 菜单按钮
        Box {
            IconButton(
                onClick = { showMenu = true },
                modifier = Modifier.size(32.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.MoreVert,
                    contentDescription = "更多选项",
                    tint = Color.Gray
                )
            }
            
            DropdownMenu(
                expanded = showMenu,
                onDismissRequest = { showMenu = false }
            ) {
                DropdownMenuItem(onClick = {
                    onEdit()
                    showMenu = false
                }) {
                    Icon(
                        imageVector = Icons.Default.Edit,
                        contentDescription = "编辑",
                        tint = Color.Gray
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("编辑名称")
                }
                
                DropdownMenuItem(onClick = {
                    onDelete()
                    showMenu = false
                }) {
                    Icon(
                        imageVector = Icons.Default.Delete,
                        contentDescription = "删除",
                        tint = Color.Gray
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("删除会话")
                }
            }
        }
    }
}

@Composable
fun EditSessionDialog(
    title: String,
    onTitleChange: (String) -> Unit,
    onDismiss: () -> Unit,
    onConfirm: () -> Unit
) {
    Dialog(onDismissRequest = onDismiss) {
        Surface(
            shape = RoundedCornerShape(8.dp),
            color = Color.White
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "编辑会话名称",
                    fontWeight = FontWeight.Bold,
                    fontSize = 18.sp
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                TextField(
                    value = title,
                    onValueChange = onTitleChange,
                    modifier = Modifier.fillMaxWidth(),
                    placeholder = { Text("请输入会话名称") },
                    singleLine = true
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    TextButton(onClick = onDismiss) {
                        Text("取消")
                    }
                    
                    Spacer(modifier = Modifier.width(8.dp))
                    
                    Button(
                        onClick = onConfirm,
                        colors = ButtonDefaults.buttonColors(backgroundColor = Blue)
                    ) {
                        Text("保存", color = Color.White)
                    }
                }
            }
        }
    }
}

@Composable
fun DeleteConfirmDialog(
    onDismiss: () -> Unit,
    onConfirm: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("删除会话") },
        text = { Text("确定要删除这个会话吗？此操作不可撤销。") },
        confirmButton = {
            Button(
                onClick = onConfirm,
                colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red)
            ) {
                Text("删除", color = Color.White)
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}
